package com.xiaoge.system.controller;


        import cn.afterturn.easypoi.excel.ExcelExportUtil;
        import cn.afterturn.easypoi.excel.entity.ExportParams;
        import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
        import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
        import com.baomidou.mybatisplus.core.metadata.IPage;
        import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
        import com.xiaoge.auth.annotation.ControllerEndpoint;
        import com.xiaoge.response.Result;
        import com.xiaoge.system.entity.Log;
        import com.xiaoge.system.entity.Menu;
        import com.xiaoge.system.entity.Role;
        import com.xiaoge.system.entity.User;
        import com.xiaoge.system.enums.RoleStatusEnum;
        import com.xiaoge.system.service.MenuService;
        import com.xiaoge.system.service.RoleService;
        import com.xiaoge.system.vo.LogVO;
        import com.xiaoge.system.vo.RoleVo;
        import com.xiaoge.system.vo.UserVo;
        import io.swagger.annotations.ApiOperation;
        import org.apache.poi.ss.usermodel.Workbook;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.util.ObjectUtils;
        import org.springframework.validation.annotation.Validated;
        import org.springframework.web.bind.annotation.*;

        import javax.servlet.ServletOutputStream;
        import javax.servlet.http.HttpServletResponse;
        import java.io.IOException;
        import java.net.URLEncoder;
        import java.util.HashMap;
        import java.util.List;
        import java.util.Map;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author xiaoge
 * @since 2021-02-02
 */
@RestController
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private MenuService menuService;
    /**
     * 分页查询角色
     *
     * @param current
     * @param size
     * @param roleVo
     * @return
     */

    /**
     * 角色授权
     *
     * @param mids
     * @return
     */
    @ControllerEndpoint(exceptionMessage = "角色授权失败", operation = "角色授权")
    @ApiOperation(value = "角色授权")
    @PostMapping("/authority")
    public Result authority(Long id, @RequestBody Long[] mids) {
        roleService.authority(id, mids);
        return Result.ok();
    }

    /**
     * 角色拥有的菜单权限id和菜单树
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "角色拥有的菜单和所有菜单")
    @GetMapping("/findRoleMenu")
    public Result findRoleMenu(Long id) {
        List<Menu> tree = menuService.permsTreeBuild(menuService.list());
        //角色拥有的菜单id
        List<Long> mids = roleService.findMenuIdsByRoleId(id);
        //List<Long> ids = menuService.findOpenIds();
        Map<String, Object> map = new HashMap<>();
        map.put("tree", tree);
        map.put("mids", mids);
        return Result.ok().data(map);
    }

    @ApiOperation(value = "分页查询角色")
    @PostMapping("/findRolePage")
    public Result findUserPage(@RequestParam(defaultValue = "1") Integer current,
                               @RequestParam(defaultValue = "7") Integer size,
                               @RequestBody RoleVo roleVo) {
        //取得分页条件
        Page<Role> page = new Page<>(current, size);
        //获得wragger
        QueryWrapper<Role> queryWrapper = getWrapper(roleVo);

        //执行查询
        IPage<Role> userPage = roleService.page(page, queryWrapper);

        long total = userPage.getTotal();
        List<Role> records = userPage.getRecords();
        return Result.ok().data("total", total).data("records", records);
    }

    @ApiOperation(value = "获取所有角色")
    @GetMapping("/getRoleList")
    public Result getRoleList() {
        List<Role>roles=roleService.list();
        return Result.ok().data("records",roles);
    }
    /**
     * 添加角色信息
     *
     * @param roleVo
     * @return
     */
    @ControllerEndpoint(exceptionMessage = "添加角色失败", operation = "添加角色")
    @ApiOperation(value = "添加角色")
    @PostMapping("/add")
    public Result add(@RequestBody RoleVo roleVo) {
        Role role =new Role();
        role.setRoleName(roleVo.getRoleName());
        role.setRemark(roleVo.getRemark());
        role.setStatus(RoleStatusEnum.AVAILABLE.getStatusCode());
        roleService.save(role);
        return Result.ok();
    }

    /**
     * 删除角色
     *
     * @param id 角色ID
     * @return
     */
    @ControllerEndpoint(exceptionMessage = "删除角色失败", operation = "删除角色")
    @ApiOperation(value = "删除角色", notes = "根据id删除角色信息")
    @DeleteMapping("/delete")
    public Result delete(Long id) {

        return roleService.delRole(id);
    }


    /**
     * 更新角色
     *
     * @param id
     * @param roleVo
     * @return
     */
    @ControllerEndpoint(exceptionMessage = "更新角色失败", operation = "更新角色")
    @ApiOperation(value = "更新角色", notes = "根据id更新角色信息")
    @PutMapping("/update")
    public Result update(Long id, @RequestBody RoleVo roleVo) {
        Role role =new Role();
        role.setId(id);
        role.setRoleName(roleVo.getRoleName());
        role.setRemark(roleVo.getRemark());
        roleService.updateById(role);
        return Result.ok();
    }

    /**
     * 更新角色状态
     *
     * @param id
     * @param status
     * @return
     */
    @ControllerEndpoint(exceptionMessage = "角色更新状态失败", operation = "角色|禁用/启用")
    @ApiOperation(value = "更新状态", notes = "禁用和更新两种状态")
    @PutMapping("/updateStatus")
    public Result updateStatus(Long id, Integer status) {
        Role role =new Role();
        role.setId(id);
        role.setStatus(status);
        roleService.updateStatus(role);
        return Result.ok();
    }

    /**
     * 导出所有角色的excel表格
     *
     * @param response
     * @throws IOException
     */
    @ControllerEndpoint(exceptionMessage = "导出角色excel失败", operation = "导出角色excel")
    @ApiOperation(value = "导出excel", notes = "导出所有角色的excel表格")
    @PostMapping("/excel")
    public void export(HttpServletResponse response) throws IOException {
        List<Role> roles = roleService.list();
        ExportParams params = new ExportParams("角色表", "角色表", ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(params, Role.class, roles);
        ServletOutputStream outputStream = null;
        try {
            response.setHeader("content-type", "application/octet-stream");
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("角色表.xls", "UTF-8"));
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private QueryWrapper<Role> getWrapper(RoleVo roleVo) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        if (roleVo != null) {
            //查询每个条件
            if (!ObjectUtils.isEmpty(roleVo.getRoleName())) {
                queryWrapper.like("role_name", roleVo.getRoleName());
            }
        }
        return queryWrapper;
    }
}
